<?php

namespace App\Http\Controllers\v1;


use App\Models\Area;
use App\Models\Banner;
use App\Models\Family;
use App\Models\Project;
use App\Models\ProjectCategory;
use App\Models\ProjectServiceObj;
use App\Models\SmsCode;
use App\Models\Team;
use App\Models\User;
use App\Models\UserCollection;
use App\Models\UserProject;
use App\Models\UserTrans;
use App\Models\Volunteer;
use App\Models\VolunteerGoodAt;
use App\Models\WechatTempMsg;
use EasyWeChat\Core\Exception;
use Illuminate\Http\Request;
use App\Libs\IdCard;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Hashids\Hashids;

class ProjectController extends Controller
{

    public function listInfo(Request $request)
    {
        $pageNum = request()->input('current_page', 1);
        $pageSize = request()->input('page_size', 10);
        $from = ($pageNum - 1)*$pageSize;

        $name = $request->input('name');
        $teamId = $request->input('team_id');
        $sort = $request->input('sort');

        $blackTeam = Team::where('org_id', $this->getOrdId())->where('in_blacklist', 1)->pluck('id')->toArray();
        $nodes = Project::with(['team','category', 'serviceObj'])->where('org_id', $this->getOrdId())->where('status', 1)->where('verify_status', 1)->whereNotIn('team_id', $blackTeam);
        if(!empty($name))//名称检索
        {
            $nodes = $nodes->where('name', 'like', "%{$name}%");
        }
        if(!empty($teamId))
        {
            $nodes = $nodes->where('team_id', $teamId);
        }

        if($request->has('service_category') && !empty($serviceCategory= $request->input('service_category')))
        {
            $serviceCategory = is_array($serviceCategory)? $serviceCategory:explode(',', $serviceCategory);
            $cateCount = count($serviceCategory);
            $pids = ProjectCategory::where('org_id', $this->getOrdId())->whereIn('service_category_name', $serviceCategory)->groupBy('project_id')->havingRaw("count(*) ={$cateCount}")->get(['project_id'])->toArray();

            $ids = array_map(function($node){
                return $node['project_id'];
            }, $pids);
            $nodes = $nodes->whereIn('id', $ids);
        }

        if($request->has('service_object') && !empty($serviceObject= $request->input('service_object')))
        {
            $serviceObject = is_array($serviceObject)? $serviceObject:explode(',', $serviceObject);
            $objCount = count($serviceObject);
            $pids = ProjectServiceObj::where('org_id', $this->getOrdId())->whereIn('service_object_name', $serviceObject)->groupBy('project_id')->havingRaw("count(*) ={$objCount}")->get(['project_id'])->toArray();

            $ids = array_map(function($node){
                return $node['project_id'];
            }, $pids);

            $nodes = $nodes->whereIn('id', $ids);
        }

        if($request->has('recommend') && !empty($recommend = $request->input('recommend')) && $recommend == 1)
        {
            $nodes = $nodes->whereRaw('recommend_time is not null');
        }

        if(($cityCode = $this->getCityCode()))
        {
            $nodes = $nodes->where('city_id', $cityCode);
        }

        $count = $nodes->count();

        $nodes = $nodes->orderBy('pri', 'asc');
        switch($sort)
        {
            case 'recommend':
                $nodes = $nodes->whereRaw('recommend_time is not null');
                break;
            case 'distance':

                //st_distance (point (lng, lat),point(113.858202,22.583819)

                list($lng1, $lat1) = explode('-', request()->header('X-location'));
                if($lng1 != 'undefined')
                {
                    $nodes = $nodes->orderByRaw("st_distance (point (lng, lat),point({$lng1}, {$lat1}))");
                }
                break;

            case 'time':

            default:
                $nodes = $nodes->orderBy('publish_time','desc');
                break;

        }

        $nodes = $nodes->orderBy('id','desc');

        $lists = $nodes->take($pageSize)->skip($from)->get();
        $list = [];
        foreach($lists as $value)
        {
            $tmp = $value->getAllInfo();
            $list[] = $tmp;
        }

        $pageInfo = [
            "current_page" => intval($pageNum),
            "total_page" => ceil($count / $pageSize),
            "page_size" => intval($pageSize)
        ];

        $data['list'] = $list;
        $data['page'] = $pageInfo;
        $this->setData($data);

        return $this->response();
    }


    public function info(Request $request, $id)
    {

        $node = Project::where('org_id', $this->getOrdId());

        $preview = $request->input('preview', 0);
        if($preview != 1)
        {
            $node = $node->where('status', 1)->where('verify_status', 1);
        }
        $node = $node->where('id', $id);
        $node = $node->first();

        if(empty($node))
        {
            $this->setStatus(10001);
            $this->setMsg('参数错误,非法ID');
            return $this->response();
        }

        $data = $node->getAllInfo();

        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();
        $userProject = UserProject::where('project_id', $id)->where('user_id', $userInfo->id)->first();
        $data['join_status'] = empty($userProject)? -1:$userProject->verify_status;
        $data['my_reward_time'] = empty($userProject)? -1:$userProject->reward_time;

        $userCollection = UserCollection::where('type', 0)->where('relation_id', $id)->where('user_id', $userInfo->id)->first();
        $data['collection_status'] = empty($userCollection)? 0:1;


        $this->setData($data);
        return $this->response();
    }


    public function join(Request $request, $id)
    {

        $rules = ['type'=>'required|in:0,1'];
        $validator = Validator::make(Input::all(), $rules);
        if($validator->fails())
        {
            $errors = $validator->errors();
            $this->setStatus(10001);
            $this->setMsg(implode(' ', $errors->all()));

            return $this->response();
        }

        $input = Input::all();

        $project = Project::where('org_id', $this->getOrdId())->where('status', 1)->where('verify_status', 1);
        $project = $project->where('id', $id);
        $project = $project->first();

        if(empty($project))
        {
            $this->setStatus(10001);
            $this->setMsg('参数错误,非法ID');
            return $this->response();
        }

        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();


        if($userInfo->volunteer->in_blacklist == 1)
        {
            $this->setStatus(10001);
            $this->setMsg('您被拉入黑名单，无法参加活动');
            return $this->response();
        }

        $type = $request->input('type');
        $userProject = UserProject::where('project_id', $id)->where('user_id', $userInfo->id)->first();
        switch($type)
        {
            case 0:
                if(empty($userProject))
                {
                    $this->setStatus(10001);
                    $this->setMsg('您还未加入该项目');
                    return $this->response();
                }
                if(time() >= strtotime($project->begin))
                {
                    $this->setStatus(10001);
                    $this->setMsg('项目已经开始,无法退出');
                    return $this->response();
                }

                $userProject->delete();
                $count = UserProject::where('project_id', $id)->where('verify_status', 1)->count();
                $project->join_people_count = $count;
                $project->save();
                return $this->response();
                break;

            case 1:
                if(!empty($userProject))
                {
                    $this->setStatus(10001);
                    $this->setMsg('您已加入该项目');
                    return $this->response();
                }

                //if(time() < strtotime($project->join_being))
                //{
                //    $this->setStatus(10001);
                //    $this->setMsg('项目还未开始招募,请等待项目开始');
                //    return $this->response();
                //}

                if(time() >= strtotime($project->join_end.' 23:59:59'))
                {
                    $this->setStatus(10001);
                    $this->setMsg('项目已过招募期');
                    return $this->response();
                }

                if($project->join_people_count >= $project->people_count)
                {
                    $this->setStatus(10001);
                    $this->setMsg('项目已满员');
                    return $this->response();
                }

                //有输入字段
                if(!empty($project->custom_config))
                {
                    foreach($project->custom_config as $val)
                    {
                        if($val['is_required'] == 1 && empty($input['extends'][$val['key']]))
                        {
                            $this->setStatus(10001);
                            $this->setMsg($val['label'].'为必填项目');
                            return $this->response();
                        }
                    }
                }

                //有输入字段
                if(!empty($project->custom_payment_config))
                {
                    foreach($project->custom_payment_config as $val)
                    {
                        if( $val['is_required'] == 1 && (empty($input['payment'][$val['key']]) ||  $input['payment'][$val['key']] < 1 ) )
                        {

                            $this->setStatus(10001);
                            $this->setMsg($val['label'].'为必买商品');
                            return $this->response();
                        }
                    }
                }

                //有购买信息
                if(!empty($input['payment']))
                {
                    foreach($project->custom_payment_config as $val)
                    {
                        $goods[$val['key']] = $val['amount'];
                    }


                    foreach($input['payment']  as $k=>$val)
                    {
                        if(!isset($goods[$k]) || $val < 1)
                        {
                            $this->setStatus(10001);
                            $this->setMsg('非法商品');
                            return $this->response();
                        }

                        $amount += $goods[$k] * $val;
                    }


                    $desc['project_id'] = $id;
                    $desc['extends'] = $input['extends'];
                    $desc['payment'] = $input['payment'];


                    $payInfo = UserTrans::joinProject($this->getOrdId(), $userInfo, $amount, $desc);

                    if($payInfo['err_code'] != 0)
                    {
                        $this->setStatus($payInfo['err_code']);
                        $this->setMsg($payInfo['err_msg']);

                        return $this->response();
                    }

                    unset($payInfo['error_code']);
                    $this->setData($payInfo);

                    return $this->response();

                }
                $userProject = new UserProject();
                $data['user_id'] = $userInfo->id;
                $data['project_id'] = $id;
                $data['verify_status'] = 0;
                $data['extends'] = $input['extends'];
                $userProject->fill($data)->save();

                //微信模版消息，团队管理员收到用户申请加入活动
                WechatTempMsg::add(50, ['project_id'=>$id, 'user_project_id'=>$userProject->id]);

                return $this->response();
                break;
        }
    }

    public function user(Request $request, $id)
    {
        $pageNum = request()->input('current_page', 1);
        $pageSize = request()->input('page_size', 10);
        $from = ($pageNum - 1)*$pageSize;

        $project = Project::where('org_id', $this->getOrdId())->where('status', 1)->where('verify_status', 1);
        $project = $project->where('id', $id);
        $project = $project->first();

        if(empty($project))
        {
            $this->setStatus(10001);
            $this->setMsg('参数错误,非法ID');
            return $this->response();
        }

        $nodes = UserProject::with(['user', 'user.volunteer'])->where('project_id', $id)->where('verify_status', 1);
        $count = $nodes->count();
        $nodes = $nodes->orderBy('id', 'desc');
        $lists = $nodes->take($pageSize)->skip($from)->get();

        $list = [];
        foreach($lists as $node)
        {
            $list[] = $node->user->getAllInfo();
        }

        $pageInfo = [
            "current_page" => intval($pageNum),
            "total_page" => ceil($count / $pageSize),
            "page_size" => intval($pageSize)
        ];

        $data['list'] = $list;
        $data['page'] = $pageInfo;
        $this->setData($data);

        return $this->response();
    }
}
